import React, { useEffect, useMemo, useRef, useState } from "react";
import { Toast, Input, Button } from "antd-mobile";
import "./index.css";

function Index() {
  const user_id = 1;
  const server_id = 2;
  const Mianref = useRef(null);
  const ws = useMemo(() => {
    return new WebSocket(
      `ws:113.44.139.133:8003/koa/ws?user_id=${user_id}&server_id=${server_id}`
    );
  }, []);

  const [chatlist, setchatlist] = useState([]);
  const [value, setValue] = useState("");
  useEffect(() => {
    ws.onopen = () => {
      console.log("连接成功");
      ws.send(JSON.stringify({ type: "getChatList" }));
    };

    ws.onmessage = (msg) => {
      const { type, data, message } = JSON.parse(msg.data);
      if (type === "getChatList") {
        console.log(data);
        setchatlist(data);
        Toast.show(message);
      } else if (type === "addMessage") {
        setchatlist((pre) => [...pre, data]);
      }
    };
  }, []);

  useEffect(() => {
    Mianref.current.scrollTop = 10000;
  }, [chatlist]);
  const handleSendMessage = () => {
    ws.send(
      JSON.stringify({
        type: "addMessage",
        data: {
          user_id,
          server_id,
          message: value,
        },
      })
    );
    setValue("");
  };
  return (
    <div className="chat">
      <div className="main" ref={Mianref}>
        {chatlist.map((item, ind) => {
          const chatItem = item.dir === 1 ? "chatitem_left" : "chatitem_right";
          const chatavatar =
            item.dir === 1 ? item.user_avatar : item.server_avatar;

          return (
            <div key={ind} className={chatItem}>
              <img className="Avatar" src={chatavatar} alt="" />
              <div>
                <div className="chatText">{item.message}</div>
              </div>
            </div>
          );
        })}
      </div>
      <div className="footer">
        <Input
          placeholder="请输入内容"
          value={value}
          onChange={(val) => {
            setValue(val);
          }}
        />
        <Button onClick={() => handleSendMessage()}>发送</Button>
      </div>
    </div>
  );
}

export default Index;
